import React, { Component } from 'react';
import {
  StyleSheet, Text, View, TouchableOpacity, Image, FlatList, TextInput, PixelRatio
} from "react-native";
import { GLOBAL } from '../../../config/global';
import { PageStatusIndex } from '../../../component/page-status/PageStatusIndex';
import { API, API_GENERATE } from '../../../config/api';
import StorageHelper from '../../../utils/storageHelper';
import { STORAGE_CONSTANT } from '../../../config/storage';
import HTTP from '../../../utils/http';
import { style } from '../../../theme/style';
import { Common } from '../../../component/common/Common.js';
import { CommonDialog } from '../../../components/common/Dialog';
import { WarningItem } from '../_component/WarningItem'
import WarningService from '../_common/service';
import { NewAccount } from '../../../components/common/newAccount';
import { SlideSelect } from '../../../components/common/slideSelect';

const scale = GLOBAL.SCALE;
const searchIcon = require('../../../imgs/global/whiteSearch.png');
const tipImg = require('../../../imgs/warning/tips3.png');

export class CreditOrderWarning extends Component {
  static navigationOptions = ({ navigation, navigationOptions }) => {
    return {
      headerTitle: '授信订单逾期',
      headerTintColor: style.color.white,
      headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack() }} color='#fff' />,
      headerRight: (<Image style={style.head.headRightEmpty} source={require('../../../imgs/goBackEmpty.png')} />),
      headerStyle: {  // 头部整体样式 
        elevation: 0,
        borderBottomWidth: 0,
        backgroundColor: style.color.themeColor
      },
      headerTitleStyle: {
        flex: 1,
        textAlign: 'center'
      }
    }
  };

  constructor(props) {
    super(props)
    this.state = {
      modalVisible: false,
      status: 'data',
      refreshIcon: false,
      listData: [{}, {}],
      alertShow: false,
      options: [],
      choice: {}
    }
    this.totalPage = 1;
    this.reload = true;
    this.pageParams = {
      searchKey: '',
      pageNo: 1,
      pageSize: 10,
      warnType: 'orderInfo'
    }
  }

  async componentWillMount () {
    await this.getSorage();
    await this.initPage();
  }

  //获取业务组织
  async  getSorage () {
    const userInfoJson = await StorageHelper.get(STORAGE_CONSTANT.USER_INFO_KEY);
    const userInfo = JSON.parse(userInfoJson);
    this.setState({
      choice: {
        corpId: userInfo.corpId || '',
        corpName: userInfo.corpName || '',
      }
    })
  }

  async initPage () {
    this.setState({
      status: this.reload ? 'loading' : 'data',
      refreshIcon: !this.reload && this.pageParams.pageNo == '1'
    })
    this.pageParams.corpId = this.state.choice.corpId;
    let res = await WarningService.getWarnList(this.pageParams);
    if (res) {
      this.totalPage = res.totalPage;
      this.setState({
        status: res.rows.length > 0 ? 'data' : 'empty',
        listData: this.pageParams.pageNo == '1' ? res.rows : this.state.listData.concat(res.rows),
        refreshIcon: false
      })
    } else {
      this.setState({
        refreshIcon: false,
        status: 'error'
      })
    }
  }

  // 刷新页面
  reloadPage = () => {
    this.pageParams.pageNo = 1;
    this.reload = true;
    this.initPage();
  }

  // 下拉刷新
  refresh () {
    this.pageParams.pageNo = 1;
    this.reload = false;
    this.initPage();
  }

  // 上拉翻页
  loadMore () {
    if (this.totalPage > this.pageParams.pageNo) {
      this.pageParams.pageNo++;
      this.reload = false;
      this.initPage();
    }
  }

  // 搜索
  _renderFilterWrap () {
    return (
      <View style={styles.filterWrap}>
        <View>
          <Image source={searchIcon} style={styles.searchIcon} />
          <TextInput
            ref="enterpriseInput"
            style={styles.searchInput}
            underlineColorAndroid='transparent'
            placeholder={"请输入企业名称/订单号/商品"}
            placeholderTextColor="rgba(255, 255, 255, .8)"
            maxLength={30}
            returnKeyType={'search'}
            defaultValue={this.pageParams.searchKey}
            onChangeText={(txt) => { this.pageParams.searchKey = txt; }}
            onSubmitEditing={() => { this.reloadPage(); }}
          />
        </View>
        <TouchableOpacity style={{ paddingLeft: 10 * scale }} onPress={() => { this.setState({ modalVisible: true }) }}>
          <Text style={{ color: '#fff' }}>如何处理？</Text>
        </TouchableOpacity>
      </View>
    )
  }

  _renderToastWrap = () => {
    return (
      <View>
        <Text style={{ fontSize: 13 * scale, marginBottom: 4 * scale }}>统计维度：已到期、有效期少于7天</Text>
        <Text style={{ fontSize: 13 * scale }}>授信销售订单存在逾期未处理时：</Text>
        <Text style={{ fontSize: 13 * scale, fontWeight: 'bold', marginTop: 20 * scale, marginBottom: 20 * scale }}>1.销售授信订单未出库将无法继续出库</Text>
        <Image style={{ width: 270 * scale, height: 84 * scale }} source={tipImg} />
      </View>
    )
  }

  _renderListItem = (data) => {
    let item = data.item
    return (
      <View>
        <WarningItem data={item} navigation={this.props.navigation} choice={this.state.choice} />
      </View>
    )
  }

  render () {
    let { modalVisible, status, listData, refreshIcon, alertShow, choice, options } = this.state
    return (
      <View style={styles.container}>
        {this._renderFilterWrap()}

        {
          status == 'data' ? (<View style={{ flex: 1, paddingTop: 20 * scale, paddingBottom: 10 * scale }}>
            <FlatList
              data={listData}
              style={{ marginLeft: 12 * scale, marginRight: 12 * scale }}
              renderItem={this._renderListItem}
              refreshing={refreshIcon}
              onRefresh={() => { this.refresh() }}
              onEndReachedThreshold={0.1}
              onEndReached={() => { this.loadMore() }}
            />
          </View>) : null
        }

        <CommonDialog
          modalVisible={modalVisible}
          title={'提示'}
          onClosePress={() => { this.setState({ modalVisible: false }) }}
          renderCustom={this._renderToastWrap} />

        {
          status != 'data' ? (<PageStatusIndex status={status} emptyText={'暂无记录'} onErrorPress={this.reloadPage} />) : null
        }
      </View>
    )
  }

}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: style.color.bgGray,
  },
  filterWrap: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    backgroundColor: style.color.themeColor,
    paddingTop: 14 * scale,
    paddingBottom: 14 * scale,
    paddingLeft: 20 * scale,
    paddingRight: 4 * scale
  },
  searchInput: {
    height: 36 * scale,
    width: 265 * scale,
    paddingLeft: 70 * scale,
    paddingRight: 12 * scale,
    backgroundColor: 'rgba(255, 255, 255, .18)',
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    paddingVertical: 0,
    position: 'relative',
    borderRadius: 8 * scale,
    color: '#fff',
    fontSize: 13 * scale
  },
  searchIcon: {
    width: 20 * scale,
    height: 22 * scale,
    position: 'absolute',
    left: 40 * scale,
    top: 8 * scale,
    zIndex: 9,
    opacity: 0.8,
  },
})